import { shell, BrowserWindow, app } from 'electron';
import { join } from 'path';
import { is } from '@electron-toolkit/utils';
import icon from '../../../resources/index.png?asset';

export let mainWindow: Electron.BrowserWindow;

export function createMainWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 900,
        height: 670,
        show: false,
        frame: false,
        autoHideMenuBar: true,
        icon,
        webPreferences: {
            preload: join(__dirname, '../preload/index.js'),
            sandbox: false,
            // contentSecurityPolicy: "script-src 'self' http://at.alicdn.com"
        } as Electron.WebPreferences
    });

    mainWindow.on('ready-to-show', () => {
        mainWindow.show();
    });

    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url);
        return { action: 'deny' };
    });

    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        mainWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/index.html`);
    } else {
        mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
    }

    mainWindow.on('close', (e) => {
        if(isShouldQuit) {
            app.quit();
            return;
        }
        e.preventDefault();
        mainWindow.hide();
    });

}

export function showMainWindow(isFocus = false) {
    mainWindow.show();
    if(isFocus) {
        mainWindow.focus();
    }
}

let isShouldQuit = false;
export function closeMainWindow() {
    isShouldQuit = true;
    mainWindow.close();
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        closeMainWindow();
        app.quit();
    }
});
